const db = require('../config/db');

class Group {
  static create(name, creatorId, callback) {
    const sql = 'INSERT INTO groups (name, creator_id) VALUES (?, ?)';
    db.run(sql, [name, creatorId], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, this.lastID);
    });
  }

  static addMember(groupId, userId, callback) {
    const sql = 'INSERT INTO group_members (group_id, user_id) VALUES (?, ?)';
    db.run(sql, [groupId, userId], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, this.lastID);
    });
  }

  static sendMessage(groupId, senderId, message, callback) {
    const sql = 'INSERT INTO group_messages (group_id, sender_id, message) VALUES (?, ?, ?)';
    db.run(sql, [groupId, senderId, message], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, this.lastID);
    });
  }

  static getMessages(groupId, callback) {
    const sql = 'SELECT * FROM group_messages WHERE group_id = ? ORDER BY timestamp ASC';
    db.all(sql, [groupId], callback);
  }

  static getUserGroups(userId, callback) {
    const sql = `
      SELECT g.id, g.name, g.creator_id, g.created_at 
      FROM groups g
      JOIN group_members gm ON g.id = gm.group_id
      WHERE gm.user_id = ?`;
    db.all(sql, [userId], callback);
  }
}

module.exports = Group; 